#!/usr/bin/node

const log = console.log;
const koa = require('koa'),
      Router = require('koa-router'),
      bodyparser = require('koa-bodyparser'),
      tasks = require('./routes/tasks.js'),
      users = require('./routes/users.js'),
      json = require('koa-json'),
      logger = require('koa-logger'),
      jwt = require('koa-jwt'),
      jwt2=require('jsonwebtoken'),
      JWT_KEY = require('./lib/constant.js');

let router = new Router();
let app = new koa();

app.use(json());
app.use(logger());
app.use(jwt({secret:JWT_KEY}).unless({path:/\api\/users\/login$/})); 
app.use(bodyparser({enableTypes:['json','form','text']}));

app.use(async(ctx,next)=>{

  //get token
  let token = ctx.request.header.Authorization;
  if(typeof token !== 'undefined'){
    token = token.split(' ')[1];
   let user = jwt2.verify(token,JWT_KEY); 
    
    console.log(`takon=${token}`);

    //parse token get user id
    ctx.userID = user.id;
  }
  await next();
})

app.use(tasks.routes());
app.use(users.routes());
app.listen(8080);

log('hello app.js');

